// 获取随机验证码
let yzmbtn = document.querySelector('.main > form > div:nth-child(10)')
var flag = true
let login = document.querySelector('.header > .content > p:nth-child(3)')


const form = document.querySelector('form')
const nameInp = document.querySelector('.main > form > input:nth-child(5)')
const pwdInp = document.querySelector('.main > form > input:nth-child(7)')
const rpwdInp = document.querySelector('.main > form > input:nth-child(12)')
const errBox = document.querySelector('.err')

form.addEventListener('submit', e => {

  e = e || window.event

  try { e.preventDefault() } catch(err) { e.returnValue = false }


  const info = {
    username: nameInp.value,
    password: pwdInp.value,
    rpassword: rpwdInp.value
  }

  if (!info.username || !info.password || !info.rpassword) return alert('请按照规则填写')

  ajax({
    url: 'http://localhost:8888/users/register',
    data: querystringify(info),
    method: 'POST',
    dataType: 'json',
    success (res) {
      // 条件判断
      console.log(res)
        if (res.code === 0) {
          // 失败
            errBox.style.display = 'block'
        }
        
        if (res.code === 1) {
            // 成功
            errBox.style.display = 'none'
            
            if (window.confirm('注册成功, 点击确定跳转到登录页, 点击取消留在当前页面')) {
            window.location.href = './login.html'
            }
        }
    }
  })
})


yzmbtn.onclick = function () {
    if (flag === false) return
    flag = false
    var time = 60
    var total = setInterval(function () {
        time--
        yzmbtn.innerText = '再次获取(' + time + 's)'
        if (time === 0) {
            clearInterval(total)
            yzmbtn.innerText = '获取验证码'
            flag = true
        }
    }, 1000)
}

login.onclick = function () {
    window.location.href = './login.html'
}